from django import http
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View

from goods.models import SKU, GoodsCategory
from meixixi.utils.my_category import get_categories
from meixixi.utils.my_constants import LIST_SKU_PER_COUNT
from meixixi.utils.response_code import RETCODE


class SKUListView(View):
    def get(self, request, category_id, page_num):
        sort = request.GET.get('sort', 'default')
        if sort == 'price':
            sort_field = 'price'
        elif sort == 'hot':
            sort_field = 'sales'
        else:
            sort_field = '-create_time'

        categories = get_categories()
        context = {
            'categories': categories
        }

        skus = SKU.objects.filter(category_id=category_id).order_by(sort_field).all()
        category = GoodsCategory.objects.get(id=category_id)
        paginate = Paginator(skus, LIST_SKU_PER_COUNT)
        page = paginate.page(page_num)
        current_page = page.object_list
        sku_list = page.object_list
        total_page = paginate.num_pages
        context = {
            'categories': categories,
            'skus': sku_list,
            'category': category,
            'sort': sort
        }
        return render(request, 'list.html', context=context)


class HotSKUListView(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]
        sku_list = []
        for sku in skus:
            sku_dict = {
                'id':sku.id,
                'default_image_url':sku.default_image_url.url,
                'name':sku.name,
                'price':sku.price
            }
            sku_list.append(sku_dict)

        return http.JsonResponse({
            'code':RETCODE.OK,
            'hot_sku_list':sku_list
        })